#encoding=utf8
'''
Created on Oct 28, 2014

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django.db import models
from django import forms
from django.utils import timezone

from core.fields import CustomCharField


CROSS_PROMO_NETWORK_NAME = 'Chartboost Cross Promo'


NETWORK_STATUS = (
    ('D', u'Display'),
    ('H', u'Hide'),
)


class Network(models.Model):
    name = models.CharField(u'Ad Network Name', max_length=100)
    status = models.CharField(u'Status', max_length=1, choices=NETWORK_STATUS,
        null=True, blank=True, default='')

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = u'Ad Networks'
        verbose_name_plural = u'Ad Network'


class UnitType(models.Model):
    name = models.CharField(u'Ad Unit Name', max_length=100)
    network = models.ForeignKey(Network, verbose_name=u'Network', null=True,
        blank=True)

    def __unicode__(self):
        return '%s - %s' % (self.network, self.name)

    class Meta:
        verbose_name = u'Unit'


ORIENTATION = (
    ('P', u'Portrait'),
    ('L', u'Landscape'),
)


YES_OR_NO = (
    ('Y', u'Yes'),
    ('N', u'No'),
)


REQUEST_STATUS = (
    ('N', u'New'),
    ('F', u'Fulfilled'),
    ('I', u'Invalid'),
    ('C', u'Cancel'),
)


class AdsInfo(models.Model):
    request_id = models.CharField(u'Request ID', max_length=20)
    app = models.ForeignKey('app_info.App', verbose_name=u'App',
        limit_choices_to={'status': 'V'})
    editor = models.EmailField(u'Editor', null=True, blank=True)
    create_time = models.DateTimeField(u'Timestamp', auto_now_add=True)
    orientation = models.CharField(u'Orientation', max_length=1,
        choices=ORIENTATION)
    cross_promo = models.CharField(u'Require Cross Promo?', max_length=1,
        choices=YES_OR_NO, default='N')
    cross_promo_ads = models.CharField(u'Cross Promo Ads', max_length=500,
        null=True, blank=True, default='')
    cross_local = models.CharField(u'Cross Promo Creatives (Local)', max_length=1000,
        default='', null=True, blank=True)
    cross_remote = models.CharField(u'Cross Promo Creatives (Dropbox)', max_length=1000,
        default='', null=True, blank=True)
    note = models.TextField(u'Other Ad Network / Notes', null=True, blank=True)
    status = CustomCharField(u'Request Status', max_length=1, choices=REQUEST_STATUS,
        default='N', widget=forms.Select(attrs={'style': '''width: 100px;'''}))

    def get_local_create_time(self):
        return timezone.localtime(self.create_time).strftime('%Y-%m-%d %H:%M:%S')

    def get_units(self, status='A'):
        return self.adsunit_set.filter(status=status)

    def __unicode__(self):
        return self.request_id

    class Meta:
        verbose_name = u'Ad Request'
        verbose_name_plural = u'Ad Request'


ADS_UNIT_STATUS = (
    ('A', u'Active'),
    ('L', u'Legacy'),
)


ACTIVATION_STATUS = (
    ('P', 'Pending'),
    ('A', 'Activated'),
    ('F', 'Failure'),
)


class AdsUnit(models.Model):
    info = models.ForeignKey(AdsInfo, verbose_name=u'Ads Info', null=True,
        blank=True)
    unit = models.ForeignKey(UnitType, verbose_name=u'Ads Unit', null=True,
        blank=True)
    value = CustomCharField(u'ID', max_length=50, null=True, blank=True,
        default='', widget=forms.TextInput(attrs={'style': '''width: 300px;'''}))
    status = models.CharField(u'Status', max_length=1, choices=ADS_UNIT_STATUS,
        null=True, blank=True, default='')

    editor = models.CharField('Fulfilled By', max_length=100, null=True, blank=True)
    timestamp = models.DateTimeField('Fulfilled At', null=True, blank=True)

    activation = models.CharField('Activation Status', max_length=1,
        choices=ACTIVATION_STATUS, null=True, blank=True, default='P')
    first_get_time = models.DateTimeField('First Time to Get At', null=True, blank=True)
    latest_get_time = models.DateTimeField('Latest Time to Get At', null=True, blank=True)
    fail_count = models.IntegerField('Failed to Activation Count', default=0)

    def __unicode__(self):
        return "%s (ID: %s)" % (self.unit, self.value)

    class Meta:
        verbose_name = u'Ads Unit'
        verbose_name_plural = u'Ads Unit'
        unique_together = ('info', 'unit')


CP_STATUS = (
    ('P', 'Pending Creation'),
    ('R', 'Ready'),
    ('I', 'Invalid'),
    ('X', 'Cancel'),
)


class CrossPromoReqManager(models.Manager):
    def get_latest_num(self):
        current_year = timezone.now().year
        current_month = timezone.now().month
        current_day = timezone.now().day
        latest = self.filter(
            create_time__year=current_year,
            create_time__month=current_month,
            create_time__day=current_day).order_by('-request_id')[:1]
        return int(latest[0].request_id[-2:]) + 1 if latest else 1


class CrossPromoReq(models.Model):
    """
    on 2016-03-01, make cross promo request independent
    """
    request_id = models.CharField('Request ID', max_length=20,
                                  unique=True)
    app = models.ForeignKey('app_info.App', verbose_name='App',
                            limit_choices_to={'status': 'V'})
    orientation = models.CharField('Orientation', max_length=1,
                                   choices=ORIENTATION)
    cross_local = models.CharField('Cross Promo Creatives (Local)',
                                   max_length=1000, null=True, blank=True)
    cross_remote = models.CharField('Cross Promo Creatives (Dropbox)',
                                    max_length=1000, null=True, blank=True)
    notes = models.TextField('Notes', null=True, blank=True)
    status = models.CharField('Status', max_length=1, choices=CP_STATUS,
                              default='P')
    create_time = models.DateTimeField('Created At', auto_now_add=True)
    editor = models.EmailField('Editor', null=True, blank=True)

    objects = CrossPromoReqManager()

    def __unicode__(self):
        return self.request_id

    def get_token(self, status='A'):
        return self.crosspromotoken_set.filter(status=status)

    class Meta:
        verbose_name = 'Cross Promo Request'
        verbose_name_plural = verbose_name


class CrossPromoVendor(models.Model):
    name = models.CharField('Vendor Name', max_length=100)
    status = models.CharField('Status', max_length=1, choices=NETWORK_STATUS,
                              default='H')

    def __unicode__(self):
        return self.name

    class Meta:
        verbose_name = 'Cross Promo Vendor'
        ordering = ('status',)


class CrossPromoTokenName(models.Model):
    name = models.CharField('Token Name', max_length=50)
    vendor = models.ForeignKey(CrossPromoVendor,
                               verbose_name='Cross Promo Vendor')

    def __unicode__(self):
        return '{obj.vendor} - {obj.name}'.format(obj=self)

    class Meta:
        verbose_name = 'Cross Promo Token Name'
        verbose_name_plural = verbose_name


class CrossPromoToken(models.Model):
    req = models.ForeignKey(CrossPromoReq, verbose_name='Cross Promo Request')
    token = models.ForeignKey(CrossPromoTokenName,
                              verbose_name='Cross Promo Token')

    value = models.TextField('Token Value', null=True, blank=True)

    status = models.CharField('Status', max_length=1, choices=ADS_UNIT_STATUS,
                              default='', null=True, blank=True)
    editor = models.EmailField('Fulfilled By', null=True, blank=True)
    timestamp = models.DateTimeField('Fulfilled At', null=True, blank=True)

    def __unicode__(self):
        return self.token

    class Meta:
        verbose_name = 'Cross Promo Token'
